import {
  collectionType,
  CollectionInfo,
  CollectionType,
  defaultModeType
} from "./type";
import { createContext, useEffect, useState, useContext, useRef } from "react";
import type { FC, PropsWithChildren } from "react";
import { getStoreItem } from "@/util/storage";
import { useSelector, useLocation, Navigate } from "react-router-dom";
let collectionConfig: collectionType;

/* 创建埋点相关配置 */
function CraeteCollection(config: collectionType) {
  const baseConfig = {
    collectPageStay: true
  };
  if (typeof config != "object") {
    throw new Error("CraeteCollection's arg mast be an Object");
  }
  collectionConfig = Object.assign(baseConfig, config);
  return null;
}
/* 定义全局共享的埋点数据 */
const CollectionContext = createContext<{
  config: object;
  usePageStayTime: (() => () => void) | (() => void);
  usePageSwitch: () => (path: string) => void;
  useClick: () => void;
}>({
  config: {},
  usePageStayTime: () => {},
  usePageSwitch: () => () => {},
  useClick: () => {}
});

/* 页面刷新和页面隐藏切换的检测 */
const usePageStayTime = () => {
  const [startTime, setStartTime] = useState(0); /* 用户活跃的时候的计时开始 */
  const [isActivty, setIsActivty] = useState(false);
  const [pageUrl, setPageUrl] = useState("");
  function setUserStatus() {
    setIsActivty(true);
  }
  /* 初始化的时候监听用户状态 */
  useEffect(() => {
    setPageUrl(window.location.href);
    window.addEventListener("mousemove", setUserStatus);
    window.addEventListener("keydown", setUserStatus);
    return () => {
      window.removeEventListener("mousemove", setUserStatus);
      window.addEventListener("keydown", setUserStatus);
    };
  }, []);

  /* 监听文档视图变化收集时间 */
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState == "visible") {
        setStartTime(Date.now());
      } else if (document.visibilityState == "hidden") {
        if (startTime !== 0) {
          const endTime = Date.now();
          if (endTime > startTime && isActivty) {
            collectionConfig?.pageStay?.stayInterval || 30000;
            const stayDuration = endTime - startTime;
            sendCollection({
              type: CollectionType.PageLive,
              pageUrl: pageUrl,
              stayDuration
            });
          }
        }
      }
    };
    window.addEventListener("visibilitychange", handleVisibilityChange);
    return () => {
      window.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [startTime, isActivty, pageUrl]);
  // 在刷新浏览器的时候重置停留时长统计
  useEffect(() => {
    const handleNavigation = () => {
      sendCollection({
        type: CollectionType.PageRefresh,
        pageUrl: pageUrl
      });
      // 重置统计数据
      setStartTime(0);
      setIsActivty(false);
    };

    window.addEventListener("beforeunload", handleNavigation);

    return () => {
      window.removeEventListener("beforeunload", handleNavigation);
    };
  }, [startTime, pageUrl]);
  return null;
};

/* 单页面切换路由的埋点 */
const usePageSwitch = (): ((path: string) => void) => {
  const [isActivty, setIsActivty] = useState(false);
  const timestamp = useRef(0);

  function setUserStatus() {
    setIsActivty(true);
  }

  useEffect(() => {
    window.addEventListener("mousemove", setUserStatus);
    return () => {
      window.removeEventListener("mousemove", setUserStatus);
    };
  }, []);

  return (href: string) => {
    if (timestamp.current && isActivty) {
      const stayDuration = new Date().getTime() - timestamp.current;
      sendCollection({
        stayDuration,
        type: CollectionType.PageSwitch,
        pageUrl: href
      });
    }
    timestamp.current = new Date().getTime();
  };
};
/* 点击事件埋点 */
const useClick = () => {
  sendCollection({
    type: CollectionType.Click,
    pageUrl: location.href
  });
};

/* 全局埋点提供的高阶组件 */
const CollectionProvider: FC<PropsWithChildren> = ({ children }) => {
  return (
    <CollectionContext.Provider
      value={{
        config: collectionConfig,
        usePageStayTime: () => {
          if (collectionConfig.collectPageStay) {
            return usePageStayTime;
          } else {
            return (() => {
              throw new Error(
                "请在 CraeteCollection 函数配置 collectPageStay 属性为 true"
              );
            })();
          }
        },
        usePageSwitch,
        useClick
      }}
    >
      {children}
    </CollectionContext.Provider>
  );
};

export const usePageStayTimeContext = () => {
  return useContext(CollectionContext);
};

function sendCollection(info: CollectionInfo) {
  let userinfo = {};
  try {
    const userinfoStr = getStoreItem("userinfo");
    if (userinfoStr) {
      userinfo = JSON.parse(userinfoStr);
    }
  } catch (error) {
    console.log("解析用户信息失败", error);
  }
  
  const user = {
    userName: userinfo?.userName || "未登录用户",
    userId: userinfo?.id || 0
  };
  console.log(user, "dasdas");
  if (collectionConfig.defaultMode === defaultModeType.Beacon) {
    let datainfo = "";
    const Obj = Object.assign(user, info);
    for (const key in Obj) {
      datainfo += `${key}=${Obj[key]}-`;
    }
    datainfo = datainfo.slice(0, datainfo.length - 1);
    navigator.sendBeacon(collectionConfig.proxyUrl + "/beacon", datainfo);
  } else if (collectionConfig.defaultMode === defaultModeType.Img) {
    const img = new Image();
    const Obj = Object.assign(user, info);
    const data = encodeURIComponent(JSON.stringify(Obj));
    img.src = `http://localhost:3000/info/pixel?data=${data}`;
  }
}

export { CraeteCollection, CollectionProvider, sendCollection };
